package com.lfy.fyadmin.config;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 跨域过滤器
 * 作为备选方案，如果WebMvcConfigurer的跨域配置不生效，可以启用此过滤器
 * 默认禁用，需要时取消@Component注释
 */
// @Component
@Order(1)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 获取请求来源
        String origin = httpRequest.getHeader("Origin");
        
        // 设置允许的源（这里允许所有源，生产环境建议限制具体域名）
        if (origin != null) {
            httpResponse.setHeader("Access-Control-Allow-Origin", origin);
        } else {
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        }
        
        // 设置允许的请求方法
        httpResponse.setHeader("Access-Control-Allow-Methods", 
            "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH");
        
        // 设置允许的请求头
        httpResponse.setHeader("Access-Control-Allow-Headers", 
            "Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma");
        
        // 设置允许携带凭证
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        
        // 设置预检请求缓存时间
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        
        // 设置暴露的响应头
        httpResponse.setHeader("Access-Control-Expose-Headers", 
            "Authorization, Content-Type, X-Total-Count");
        
        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        
        // 继续执行后续过滤器
        chain.doFilter(request, response);
    }
}